import React, { Component } from 'react'
import { LeftOutline } from 'antd-mobile-icons'
import { SearchBar, Toast } from 'antd-mobile'
import './index.scss'

export default class Search extends Component {
  state = {
    his: localStorage.getItem('his') ? [...new Set(JSON.parse(localStorage.getItem('his')))].slice(0, 10) : []
  }

  render() {
    return (
      <div className='search'>
        <div className="item-head">
          <div className="back" onClick={() => this.props.history.go(-1)}>
            <LeftOutline />
          </div>
          <div className="gosearch1" >
            <SearchBar placeholder='请输入内容' showCancelButton onSearch={this.submitSearch} />
          </div>
          <div className="changestyle"></div>
        </div>
        <div className='hissearch'>
          <div>
            <strong>搜索记录</strong>
          </div>
          <ul>
            {
              this.state.his.map((item, index) => (
                <li key={index} onClick={(e) => this.clickhis(e, item)}>{item}</li>
              ))
            }
          </ul>
        </div>
      </div>
    )
  }
  componentWillUnmount() {
    this.setState = () => false;
  }
  submitSearch = async (value) => {
    if (!value.trim()) {
      Toast.show({
        icon: 'fail',
        content: '还没输入'
      })
      return false
    }
    let history = localStorage.getItem('his') ? JSON.parse(localStorage.getItem('his')) : []
    history.unshift(value)
    localStorage.setItem('his', JSON.stringify(history))
    await this.setState({
      his: localStorage.getItem('his') ? [...new Set(JSON.parse(localStorage.getItem('his')))] : []
    })
    if (this.state.his.length > 10) {
      this.setState({
        his: [...new Set(this.state.his.slice(0, 10))]
      })
    }
    this.props.history.push({
      pathname: '/SearchRes',
      query: value
    });
  }
  clickhis = (e, item) => {
    this.props.history.push({
      pathname: '/SearchRes',
      query: item
    });
  }
}
